package com.problem.leetcode;

public class Problem27_1 {

    //end的指针前移 但是 中间出现了问题  这种要如何处理

    public int removeElement(int[] nums, int val) {

        if (nums.length <= 0) {
            return -1;
        }

        int begin = 0, middle = nums.length - 1, end = nums.length - 1;

        while (begin < middle) {
            if (nums[begin] == val && nums[middle] != val) {
                swap(nums, begin, middle);
                ++begin;
                if (middle == end) {
                    --middle;
                    --end;
                }
            } else if (nums[begin] == val && nums[middle] == val) {
                while (nums[end] == val && begin < end) {
                    --end;
                    middle = end;
                }

                if (begin <= end) {
                    swap(nums, begin, end);
                    ++begin;
                    --end;
                    middle = end;
                }
            } else if ((nums[begin] != val && nums[middle] != val)) {
                ++begin;
                --middle;
            } else if (nums[begin] != val && nums[middle] == val) {
                if (middle == end) {
                    --middle;
                    --end;
                } else {
                    swap(nums, middle, end);
                    --middle;
                    ++begin;
                    --end;
                }
            }
        }
        return end + 1;
    }

    public void swap(int[] nums, int begin, int end) {
        int tmp = nums[begin];
        nums[begin] = nums[end];
        nums[end] = tmp;
    }

    public static void main(String[] args) {
        int[] nums = {0, 1, 2, 2, 3, 0, 4, 2};
        int result = new Problem27_1().removeElement(nums, 2);

        for (int index = 0; index < nums.length; index++) {
            System.out.println(nums[index]);
        }
    }

}
